<template>
  <teleport to="body">
    <CreateView :body-style="{height: '100%'}">
      <template v-slot:header>
        <div class="header">
          <span class="text">{{ dialogTitle }}</span>
          <i class="el-icon-close rt" @click="close"/>
        </div>
      </template>

      <div v-loading="newLoading" class="new-journal">
        <div class="content">
          <el-tabs v-model="activeName" @tab-click="tabClick">
            <template v-for="(item, index) in tabsData" :key="index">
              <el-tab-pane :label="item.label" :name="item.key"/>
            </template>
          </el-tabs>
          <div class="form">
            <template v-for="(item, index) in formList" :key="index">
              <div class="row-list">
                <label class="item-label">{{ item.label }}：</label>
                <el-input :autosize="{ minRows: 4}"
                          :maxlength="1000"
                          v-model="formData[item.model]"
                          show-word-limit
                          type="textarea"
                          placeholder="请输入内容"
                          resize="none"/>
              </div>
            </template>

            <!-- 图片附件 -->
            <div class="img-accessory">
              <div class="img-box">
                <el-upload ref="imageUploadRef"
                           :action="crmFileSaveUrl"
                           :headers="httpHeader"
                           :data="{type: 'img', batchId: batchId}"
                           :on-preview="handleFilePreview"
                           :before-remove="beforeRemove"
                           :on-success="imgFileUploadSuccess"
                           :file-list="imageFileList"
                           name="file"
                           multiple
                           accept="image/*"
                           list-type="picture-card">
                  <p class="add-img">
                    <span class="el-icon-picture"/>
                    <span>添加图片</span>
                  </p>
                  <i class="el-icon-plus"/>
                </el-upload>
              </div>
              <p class="add-accessory">
                <el-upload ref="fileUploadRef"
                           :action="crmFileSaveUrl"
                           :headers="httpHeader"
                           :data="{type: 'file', batchId: batchId}"
                           :on-preview="handleFilePreview"
                           :before-remove="handleFileRemove"
                           :on-success="fileUploadSuccess"
                           :file-list="fileList"
                           name="file"
                           multiple
                           accept="*.*">
                  <p>
                    <i class="wukong wukong-file"/>
                    添加附件
                  </p>
                </el-upload>
              </p>
            </div>
            <div class="sent-who">
              <span class="cursor-default">发送给：</span>
              <template v-for="(item, index) in showSendUserList" :key="index">
                <span class="send-user">
                  <el-tooltip placement="bottom" effect="light" popper-class="tooltip-change-border">
                    <template v-slot:content>
                      <div>
                        <span>{{ item.realname }}</span>
                      </div>
                    </template>

                    <XrAvatar :name="item.realname" :size="26" :src="item.img" class="item-img"/>
                  </el-tooltip>
                </span>
              </template>

              <MembersDep :content-block="false" :user-checked-data="formData.sendUserList"
                          :dep-checked-data="formData.sendDeptList || []"
                          @popoverSubmit="sendUserChange">
                <template v-slot:membersDep>
                  <span>
                    <el-tooltip placement="bottom" effect="light" popper-class="tooltip-change-border">
                      <template v-slot:content>
                        <div>
                        <span>{{ sendUserDeptNames }}</span>
                        </div>
                      </template>

                      <i v-show="(formData.sendUserList.length + (formData.sendDeptList ? formData.sendDeptList.length : 0)) > 5"
                         class="el-icon-more more-user-btn"/>
                    </el-tooltip>

                    <i class="el-icon-plus add-user-btn"/>
                  </span>
                </template>
              </MembersDep>
            </div>
            <RelatedBusiness :margin-left="'0'" :all-data="allData" @checkInfos="checkInfos"/>
          </div>
        </div>
        <div class="btn-group">
          <el-button type="primary" @click="submitBtn">提交</el-button>
          <el-button @click="close">取消</el-button>
        </div>
      </div>
    </CreateView>
  </teleport>
</template>

<script setup>
import CreateView from '/src/components/CreateView'
// 部门员工优化版
import MembersDep from '/src/components/SelectEmployee/MembersDep'
// 相关信息 - 选中列表
import RelatedBusiness from '/src/components/RelatedBusiness'
import XrAvatar from "@/szcomponent/XrAvatar/index.vue";
import axios from 'axios'
import {crmFileDeleteAPI, crmFileSaveUrl} from '/src/api/common'
import {guid, getImageData} from '/src/utils'
import {useRoute, useRouter} from "vue-router"
import {getCurrentInstance} from "vue"


defineOptions({
  name: "NewDialog"
})
const props = defineProps({
  formData: Object,
  dialogTitle: {
    type: String,
    default: '写日志'
  },
  // 附件
  accessoryFileList: {
    type: Array,
    default: () => {
      return []
    }
  },
  imgFileList: {
    type: Array,
    default: () => {
      return []
    }
  },
  newLoading: Boolean
})

const imageUploadRef = ref()
const fileUploadRef = ref()

const route = useRoute()
const router = useRouter()

const emits = defineEmits([])

const cxt = getCurrentInstance()
const bus = cxt.appContext.config.globalProperties.$bus
const $wkPreviewFile = cxt.appContext.config.globalProperties.$wkPreviewFile

const optionData = reactive({
  activeName: '1',
  tabsData: [
    {label: '日报', key: '1'},
    {label: '周报', key: '2'},
    {label: '月报', key: '3'}
  ],
  // 表格数据
  formList: [],
  dateList: [
    {label: '今日工作内容', model: 'content'},
    {label: '明日工作内容', model: 'tomorrow'},
    {label: '遇到的问题', model: 'question'}
  ],
  weekList: [
    {label: '本周工作内容', model: 'content'},
    {label: '下周工作内容', model: 'tomorrow'},
    {label: '遇到的问题', model: 'question'}
  ],
  monthList: [
    {label: '本月工作内容', model: 'content'},
    {label: '下月工作内容', model: 'tomorrow'},
    {label: '遇到的问题', model: 'question'}
  ],
  batchId: guid(),
  imageFileList: [],
  fileList: [],
  // 发送给谁
  dialogVisible: false,
  // 获取选择的数据id数组
  relevanceAll: {},
  allData: {}
})

const {
  activeName,
  tabsData,
  formList,
  dateList,
  weekList,
  monthList,
  batchId,
  imageFileList,
  fileList,
  dialogVisible,
  relevanceAll,
  allData
} = toRefs(optionData)


const httpHeader = computed(() => {
  return {
    'Admin-Token': axios.defaults.headers['Admin-Token']
  }
})

const showSendUserList = computed(() => {
  const sendUserList = props.formData.sendUserList || []
  const sendDeptList = props.formData.sendDeptList || []
  return sendUserList.concat(sendDeptList).slice(0, 5)
})

const sendUserDeptNames = computed(() => {
  const sendUserName = props.formData.sendUserList && props.formData.sendUserList.length > 0 ? `${props.formData.sendUserList.length}个员工` : ''
  const sendDeptName = props.formData.sendDeptList && props.formData.sendDeptList.length > 0 ? `${props.formData.sendDeptList.length}个部门` : ''
  const names = []
  if (sendUserName) {
    names.push(sendUserName)
  }
  if (sendDeptName) {
    names.push(sendDeptName)
  }

  return `等${names.join('和')}`
})

onMounted(() => {
  optionData.formList = optionData.dateList

  // 确定显示哪一种日志
  if (props.formData.categoryId) {
    switch (props.formData.categoryId) {
      case 1:
        optionData.tabsData = [{label: '日报', key: '1'}]
        optionData.formList = optionData.dateList
        optionData.activeName = '1'
        break
      case 2:
        optionData.tabsData = [{label: '周报', key: '2'}]
        optionData.formList = optionData.weekList
        optionData.activeName = '2'
        break
      case 3:
        tabsData.tabsData = [{label: '月报', key: '3'}]
        optionData.formList = optionData.monthList
        optionData.activeName = '3'
        break
    }
  }

  if (props.dialogTitle != '写日志' && props.formData.batchId) {
    optionData.batchId = props.formData.batchId
  }

  // 编辑时引用 - 自动勾选
  let allData = {};
  allData.business = (props.formData.businessList || []).map(item => {
    if (item.id) {
      item.businessId = item.id
    }
    return item
  })
  allData.contacts = (props.formData.contactsList || []).map(item => {
    if (item.id) {
      item.contactsId = item.id
    }
    return item
  })
  allData.contract = (props.formData.contractList || []).map(item => {
    if (item.id) {
      item.contractId = item.id
    }
    return item
  })
  allData.customer = (props.formData.customerList || []).map(item => {
    if (item.id) {
      item.customerId = item.id
    }
    return item
  })
  optionData.allData = allData
  let relevanceAll = {}
  relevanceAll.businessIds = allData.business.map(item => item.businessId)
  relevanceAll.contactsIds = allData.contacts.map(item => item.contactsId)
  relevanceAll.contractIds = allData.contract.map(item => item.contractId)
  relevanceAll.customerIds = allData.customer.map(item => item.customerId)
  optionData.relevanceAll = relevanceAll

  optionData.imageFileList = props.imgFileList.map(item => item)

  for (let index = 0; index < optionData.imageFileList.length; index++) {
    setImageList(optionData.imageFileList[index], index)
  }

  optionData.fileList = props.accessoryFileList.map(item => item)
})


/**
 * 获取图片内容
 */
function setImageList(item, index) {
  getImageData(item.url).then((data) => {
    item.url = data.src
    optionData.imageFileList.splice(index, 1, item)
  }).catch(() => {
  })
}

function close() {
  if (route.query.routerKey == 1) {
    router.go(-1)
  } else {
    emits('close')
  }
}

function tabClick() {
  switch (optionData.activeName) {
    case '1':
      optionData.formList = optionData.dateList
      break
    case '2':
      optionData.formList = optionData.weekList
      break
    case '3':
      optionData.formList = optionData.monthList
      break
  }
}

// 提交按钮
function submitBtn() {
  if (
      props.formData.content ||
      props.formData.tomorrow ||
      props.formData.question
  ) {
    emits('submitBtn',
        optionData.activeName,
        optionData.batchId,
        optionData.relevanceAll
    )
  } else {
    ElMessage.error({message: '内容至少填写一项'})
  }
}

// 图片和附件
// 上传图片
function imgFileUploadSuccess(response, file, fileList) {
  optionData.imageFileList = fileList
}

// 查看图片
function handleFilePreview(file) {
  if (file.response || file.fileId) {
    let perviewFile
    if (file.response) {
      perviewFile = file.response.data
    } else {
      perviewFile = file
    }
    $wkPreviewFile.preview({
      index: 0,
      data: [perviewFile]
    })
  }
}

function beforeRemove(file, fileList) {
  if (file.response || file.fileId) {
    let fileId
    if (file.response) {
      fileId = file.response.data.fileId
    } else {
      fileId = file.fileId
    }
    ElMessageBox.confirm('您确定要删除该文件吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
        .then(() => {
          crmFileDeleteAPI({
            id: fileId
          })
              .then(res => {
                ElMessage.success({message: '操作成功'})
                let removeIndex = getFileIndex(
                    imageUploadRef.value.uploadFiles,
                    fileId
                )
                if (removeIndex != -1) {
                  imageUploadRef.value.uploadFiles.splice(removeIndex, 1)
                }
                removeIndex = getFileIndex(props.imgFileList, fileId)
                if (removeIndex != -1) {
                  props.imgFileList.splice(removeIndex, 1)
                }
              })
              .catch(() => {
              })
        })
        .catch(() => {
          ElMessage.message({
            type: 'info',
            message: '已取消操作'
          })
        })
    return false
  } else {
    return true
  }
}

// 附件索引
function getFileIndex(files, fileId) {
  var removeIndex = -1
  for (let index = 0; index < files.length; index++) {
    const item = files[index]
    let itemFileId
    if (item.response) {
      itemFileId = item.response.data.fileId
    } else {
      itemFileId = item.fileId
    }
    if (itemFileId == fileId) {
      removeIndex = index
      break
    }
  }
  return removeIndex
}

function fileUploadSuccess(response, file, fileList) {
  optionData.fileList = fileList
}

function handleFileRemove(file, fileList) {
  if (file.response || file.fileId) {
    let fileId
    if (file.response) {
      fileId = file.response.data.fileId
    } else {
      fileId = file.fileId
    }
    ElMessageBox.confirm('您确定要删除该文件吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
        .then(() => {
          crmFileDeleteAPI({
            id: fileId
          })
              .then(res => {
                ElMessage.success({message: '操作成功'})
                let removeIndex = getFileIndex(
                    fileUploadRef.value.uploadFiles,
                    fileId
                )
                if (removeIndex != -1) {
                  fileUploadRef.value.uploadFiles.splice(removeIndex, 1)
                }
                removeIndex = getFileIndex(optionData.fileList, fileId)
                if (removeIndex != -1) {
                  optionData.fileList.splice(removeIndex, 1)
                }
              })
              .catch(() => {
              })
        })
        .catch(() => {
          ElMessage.message({
            type: 'info',
            message: '已取消操作'
          })
        })
    return false
  } else {
    return true
  }
}

function sendUserChange(users, depts) {
  props.formData.sendUserList = users
  props.formData.sendDeptList = depts
}

// 取消
function handleClose() {
  optionData.dialogVisible = false
}

function checkInfos(val) {
  optionData.relevanceAll = val
}
</script>


<style scoped lang="scss">
.new-journal {
  display: flex;
  flex-direction: column;
  height: 100%;

  .header {
    height: 40px;
    line-height: 40px;
    padding: 0 10px;

    .el-icon-close {
      display: block;
      font-size: 24px;
      color: #909399;
      margin-right: -10px;
      padding: 10px;
      cursor: pointer;
    }

    .el-icon-close:hover {
      color: $xr-color-primary;
    }

    .text {
      font-size: 17px;
      font-weight: bold;
    }
  }

  .content {
    flex: 1;
    display: flex;
    flex-direction: column;
    overflow: auto;
    padding: 20px;
  }

  .btn-group {
    text-align: right;
    padding-right: 20px;
  }

  .content :deep( .el-tabs) {
    .el-tabs__header {
      .el-tabs__item {
        height: 50px;
        line-height: 50px;
      }

      .el-tabs__nav {
        margin-left: 20px;
        font-size: 13px;
      }

      .el-tabs__nav-wrap::after {
        height: 1px;
      }
    }

    .el-tabs__content {
      padding: 0 20px;
    }
  }
}

.form {
  flex: 1;
  margin-top: 10px;
  padding: 0 20px;
  overflow-y: scroll;

  .row-list {
    margin-bottom: 20px;
    padding-bottom: 10px;

    .item-label {
      margin-bottom: 9px;
      display: block;
      font-size: 12px;
      // padding-bottom: 10px;
    }

    .el-textarea {
      .el-textarea__inner {
        resize: none;
      }
    }
  }

  .img-accessory {
    font-size: 12px;

    img {
      vertical-align: middle;
    }

    .img-box :deep( .el-upload) {
      width: 80px;
      height: 80px;
      line-height: 90px;
    }

    .img-box :deep( .el-upload-list) {
      .el-upload-list__item {
        width: 80px;
        height: 80px;
      }
    }

    .img-box {
      position: relative;
      margin-top: 40px;

      .add-img {
        position: absolute;
        left: 0;
        top: -30px;
        height: 20px;
        line-height: 20px;
        margin-bottom: 10px;
        color: #2362fb;
      }
    }

    .add-accessory {
      margin-top: 25px;
      margin-bottom: 20px;
      color: #2362fb;

      .wukong-file {
        font-size: 13px;
      }
    }
  }

  .sent-who {
    margin-bottom: 15px;

    .add-user-btn {
      border: 1px dotted #666;
      border-radius: 50%;
      padding: 5px;
      font-size: 12px;
      transform: scale(0.8);
      margin-left: 7px;
    }

    &:hover {
      color: $xr-color-primary;

      .add-user-btn {
        border-color: $xr-color-primary;
      }
    }

    // 参与人
    .send-user {
      position: relative;
      display: inline-block;

      .item-img {
        vertical-align: middle;
      }
    }

    .send-user + .send-user {
      margin-left: 7px;
    }

    .more-user-btn {
      background-color: #f3f7ff;
      border-radius: 50%;
      padding: 5px;
      font-size: 12px;
      color: #666;
      margin-left: 7px;
      cursor: pointer;

      &:hover {
        background-color: $xr-color-primary;
        color: white;
      }
    }

    .cursor-default {
      cursor: default;
      color: #666;
    }
  }
}
</style>
